package com.insigma.business.qrcode.common.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Slf4j
@Component
public class PdfUtils {

    private static String classification = "avatar";


    public static String extractImageFromPathToOss(String url, String idCardNo, String tmpDir) {
        File pdfFile = null;
        File imageFile = null;
        try {
            File dirFile = new File(tmpDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            String pdfFileName  = UUID.randomUUID().toString() + ".pdf";
            pdfFile = new File(tmpDir + pdfFileName);
            FileUtils.copyURLToFile(new URL(url), pdfFile);

            String image = extractImages(pdfFile, tmpDir);
            if (Strings.isNotBlank(image)) {
                imageFile = new File(image);

                int beginIndex = image.lastIndexOf(".");
                if (beginIndex == -1) {
                    return null;
                }

                String extName = image.substring(beginIndex, image.length());
                String objectKey = classification + "/" + idCardNo + "/" + idCardNo  + extName;
//                String result = OssUtil.saveFile(imageFile, objectKey);
//                return result;
                return null;
            }

        } catch (Exception e) {
            log.error("extractImageFromPathToOss error : {}", e);
        } finally {

            if (pdfFile != null) {
                pdfFile.delete();
            }

            if (imageFile != null) {
                imageFile.delete();
            }
        }
        return null;
    }


    public static String extractImages(File file, String targetFolder) {
        try{
            PDDocument document = PDDocument.load(file);

            List<PDPage> pages = document.getDocumentCatalog().getAllPages();
            Iterator<PDPage> iter = pages.iterator();
            int count = 0;
            while( iter.hasNext()){
                PDPage page = (PDPage)iter.next();
                PDResources resources = page.getResources();
                Map<String, PDXObjectImage> images = resources.getImages();
                if(images != null)
                {
                    Iterator<String> imageIter = images.keySet().iterator();
                    while(imageIter.hasNext())
                    {
                        count++;
                        String key = (String)imageIter.next();
                        PDXObjectImage image = (PDXObjectImage)images.get( key );
                        String name = file.getName() + "_" + count;
                        image.write2file(targetFolder + name);
                        return targetFolder + name + "." + image.getSuffix();
                    }
                }
            }
        } catch(IOException ex){
            log.error("extract images error:{}", ex);
            return null;
        }
        return null;
    }


    public static void main(String[] args) throws IOException, DocumentException {
        addImgToPdf();
    }

    private static void addImgToPdf() throws IOException, DocumentException {
        
        String templatePath = "C:\\Users\\jin\\Desktop\\44.pdf";
        
        String newPDFPath = "d:\\shouju_fb3.pdf";
        
        String fieldName = "f1";
        
        String imagePath = "C:\\Users\\jin\\Desktop\\ui\\aa.png";

        
        InputStream input = new FileInputStream(new File(templatePath));
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newPDFPath));
        
        AcroFields form = stamper.getAcroFields();


        form.setField("f2", "abc");

        
        int pageNo = form.getFieldPositions(fieldName).get(0).page;
        Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
        float x = signRect.getLeft();
        float y = signRect.getBottom();

        
        Image image = Image.getInstance(imagePath);
        
        PdfContentByte under = stamper.getOverContent(pageNo);
        
        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
        
        image.setAbsolutePosition(x, y);
        under.addImage(image);
        stamper.close();
        reader.close();
    }

    public static void fillTemplate() {
        
        String templatePath = "C:\\Users\\jin\\Desktop\\44.pdf";
        
        String newPDFPath = "d:\\shouju_fb3.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();



            stamper.setFormFlattening(true);
            stamper.close();

            String imgpath="C:\\Users\\jin\\Desktop\\ui\\aa.png";
            Rectangle signRect = form.getFieldPositions("f1").get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();
            
            Image image = Image.getInstance(imgpath);
            
            PdfContentByte under = stamper.getOverContent(1);
            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            image.setAbsolutePosition(x, y);
            under.addImage(image);

            FileOutputStream fos = new FileOutputStream("d:\\shouju_fb.pdf");
            fos.write(bos.toByteArray());

        } catch (Exception e) {
            System.out.println(e);
        }

    }

}
